<?php
namespace App\Controllers;

use App\Models\Score;
use Exception;

class ScoreController { 
    private $scoreModel;

    public function __construct() {
        $this->scoreModel = new Score();
    }

    /**
     * 获取学生课程成绩
     * GET /api/scores?sid=081106
     */
    public function getCourseScoreAction() {
        // 1. 获取请求参数
        $sid = $_GET['sid'] ?? '';
        
        // 2. 参数验证
        if (empty($sid)) {
            $this->sendErrorResponse(400, "缺少必要参数: sid");
            return;
        }

        try {
            // 3. 调用模型方法
            $scores = $this->scoreModel->getCourseScore($sid);
            
            // 4. 返回成功响应
            $this->sendSuccessResponse([
                'student_id' => $sid,
                'scores' => $scores,
                'total_courses' => count($scores)
            ]);
        } catch (Exception $e) {
            $this->sendErrorResponse(500, "获取成绩失败: " . $e->getMessage());
        }
    }

    /**
     * 按课程名或专业搜索成绩
     * GET /api/scores/search?courseName=数据结构&major=计算机&page=1&limit=10
     */
    public function searchByCourseOrMajorAction() {
        // 1. 获取请求参数
        $courseName = $_GET['courseName'] ?? null;
        $major = $_GET['major'] ?? null;
        $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
        $limit = isset($_GET['limit']) ? (int)$_GET['limit'] : 10;
        
        // 2. 参数验证
        if (empty($courseName) && empty($major)) {
            $this->sendErrorResponse(400, "至少需要提供课程名或专业参数");
            return;
        }

        // 验证分页参数
        if ($page < 1) $page = 1;
        if ($limit < 1 || $limit > 100) $limit = 10; // 限制每页最多100条记录

        try {
            // 3. 调用模型方法
            $results = $this->scoreModel->searchByCourseOrMajor($courseName, $major, $page, $limit);
            
            // 4. 返回成功响应
            $this->sendSuccessResponse([
                'query' => [
                    'courseName' => $courseName,
                    'major' => $major,
                    'page' => $page,
                    'limit' => $limit
                ],
                'results' => $results['data'],
                'pagination' => [
                    'total' => $results['total'],
                    'page' => $results['page'],
                    'limit' => $results['limit'],
                    'pages' => $results['pages']
                ]
            ]);
        } catch (Exception $e) {
            $this->sendErrorResponse(500, "搜索失败: " . $e->getMessage());
        }
    }

    /**
     * 删除成绩记录
     * DELETE /api/scores?sid=081106&cid=C101
     */
    public function deleteScoreAction() {
        // 1. 获取请求参数
        $sid = $_GET['sid'] ?? '';
        $cid = $_GET['cid'] ?? '';
        
        // 2. 参数验证
        if (empty($sid) || empty($cid)) {
            $this->sendErrorResponse(400, "缺少必要参数: sid 或 cid");
            return;
        }

        try {
            // 3. 调用模型方法
            $result = $this->scoreModel->deleteScore($sid, $cid);
            
            // 4. 处理删除结果
            if ($result) {
                $this->sendSuccessResponse([
                    'message' => "成绩记录删除成功",
                    // 修复点：使用$result替代直接访问conn
                    'affected_rows' => $result
                ]);
            } else {
                $this->sendErrorResponse(404, "未找到匹配的成绩记录");
            }
        } catch (Exception $e) {
            $this->sendErrorResponse(500, "删除成绩失败: " . $e->getMessage());
        }
    }

    /**
     * 更新成绩
     * PUT /api/scores?sid=081106&cid=C101&score=95
     */
    public function updateScoreAction() {
        // 1. 获取请求参数
        $sid = $_GET['sid'] ?? '';
        $cid = $_GET['cid'] ?? '';
        $score = $_GET['score'] ?? '';
        
        // 2. 参数验证
        if (empty($sid) || empty($cid) || empty($score)) {
            $this->sendErrorResponse(400, "缺少必要参数: sid, cid 或 score");
            return;
        }

        try {
            // 3. 调用模型方法
            $result = $this->scoreModel->updateScore($sid, $cid, $score);
            
            // 4. 处理更新结果
            if ($result) {
                $this->sendSuccessResponse([
                    'message' => "成绩更新成功",
                    'student_id' => $sid,
                    'course_id' => $cid,
                    'new_score' => $score
                ]);
            } else {
                $this->sendErrorResponse(404, "未找到匹配的成绩记录");
            }
        } catch (Exception $e) {
            $this->sendErrorResponse(400, $e->getMessage()); // 捕获模型层的验证异常
        }
    }

     /**
     * 发送成功响应
     */
    private function sendSuccessResponse($data) {
        header('Content-Type: application/json');
        http_response_code(200);
        echo json_encode([
            'status' => 'success',
            'data' => $data
        ], JSON_UNESCAPED_UNICODE);
    }

    /**
     * 发送错误响应
     */
    private function sendErrorResponse($statusCode, $message) {
        header('Content-Type: application/json');
        http_response_code($statusCode);
        echo json_encode([
            'status' => 'error',
            'message' => $message
        ], JSON_UNESCAPED_UNICODE);
    }
}
?>